package com.example.xmppchatter;

import java.util.ArrayList;
import listViewDataStructures.ChatMessage;
import com.example.xmppchatter.R;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;

/**
 * Classe Adapter per visualizzare gli elementi della ListView dell'ActivityChat. Estende la classe BaseAdapter.
 * @author giulio
 */
public class AdapterBubbleListView extends BaseAdapter {
	
	private ArrayList <ChatMessage> data;
	private Context context;
	
	public AdapterBubbleListView(ArrayList<ChatMessage> d, Context c ) {
		super();
		data = d;
		context = c;		
	}
	
	@Override
	public int getCount() {
		return data.size();
	}

	@Override
	public Object getItem(int position) {
		return data.get(position);
	}

	@Override
	public long getItemId(int position) {
		// non implementato
		return position;
	}

	@Override	
	public View getView(int position, View convertView, ViewGroup parent) {
		
		ChatMessage msg = (ChatMessage) this.getItem(position);
		
		View view = convertView;
		
		// prelevo il layout inflater
		LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		
		if (convertView == null)
			view = inflater.inflate(R.layout.row_bubble_listview, parent, false);
		
		TextView messageBody = (TextView) view.findViewById(R.id.textview_message_body);
		TextView dateAndTime = (TextView) view.findViewById(R.id.textview_date_and_time);
		RelativeLayout layout = (RelativeLayout) view.findViewById(R.id.relativelayout_bubble_row);
		
		RelativeLayout.LayoutParams lp = (LayoutParams) layout.getLayoutParams();
				
		if (msg.isMine()) {
			
			// formattalo come se fosse un mio messaggio
			layout.setBackgroundResource(R.drawable.speech_bubble_me);
			lp.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
			lp.addRule(RelativeLayout.ALIGN_PARENT_LEFT, 0);
			//lp.removeRule(RelativeLayout.ALIGN_PARENT_LEFT);
			//lp.setMargins(left, top, right, bottom);
			lp.setMargins(60, 15, 2, 0);
								
		} else {
			
			// formattalo come un messaggio inviato dall'utente remoto
			layout.setBackgroundResource(R.drawable.speech_bubble_friend);
			lp.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
			lp.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, 0);
			//lp.removeRule(RelativeLayout.ALIGN_PARENT_RIGHT);
			lp.setMargins(2, 15, 60, 0);
		}
		
		messageBody.setText(msg.getMessage());
		dateAndTime.setText(msg.getTime());
				
		return view;
	}
	
	// Rende gli elementi della lista non cliccabili
	@Override
	public boolean isEnabled(int position) {
		return false;
	}
}
